import { useTokenStore } from '@/stores/mytoken'
import request from '@/utils/request'
import requests from '@/api/requests'
//用户登录-参数类型
type LoginInfo = {
  uname: string
  code?: string
  pass: string
}
//用户登录-返回类型
type LoginResult = {
  success: Boolean
  state: number
  message: string
  content: string
}
type regInfo = {
  uname: string
  pass: string
  checkPass: string
  realname: string
  dept:string
}
export const login = (loginInfo:LoginInfo) => {
  return requests<LoginResult>({
    method: 'POST',
    url: '/login',
    data: `email=${loginInfo.uname}&password=${loginInfo.pass}`,
  })
}
export const register = (regInfo:regInfo) => {
  return requests<LoginResult>({
    method: 'POST',
    url: '/register',
    data: `email=${regInfo.uname}&password=${regInfo.pass}&realname=${regInfo.realname}&dept=${regInfo.dept}`,
  })
}
//获取用户信息
type UserInfo = {
  success: boolean
  message: string
  state: number
  content: {
    isUpdatedPassword: boolean
    portrait: string
    userName: string
  }

}
export const getInfo = () => {
  return request<UserInfo>({
    method:'GET',
    url:'/front/user/getInfo',
  })
}
//用户退出
export const logOut = () => {
  return requests({
    method:'POST',
    url:'/logout',
  })
}
//刷新token
type RToken = {
  message: string
  state: string
  success: boolean
  content: string
}
let promiseRT: Promise<any>
let isRefreshing = false
export const refreshToken = () => {
  if (isRefreshing) {
    return promiseRT
  }
  isRefreshing = true
  promiseRT = request<RToken>({
    method:'POST',
    url:'/front/user/refresh_token',
    params: {
      refreshtoken: useTokenStore().token//?.refresh_token
    }
  }).finally(()=>{
    isRefreshing = false
  })
  return promiseRT
}
